<?
require_once('includes/config.php');
require_once('includes/functions/func.global.php');
require_once('includes/classes/class.template_engine.php');

// Connect to database
db_connect($config);

// Start the session
session_start();

// Initiate return var
$digs[0] = 0;

// Check user is logged in
if(isset($_SESSION['duser']['id']))
{
	if(!isset($_SESSION['dugg'][$_GET['i']]))
	{
		// Lookup digs table to see if they have already dugg this
		$dugg = mysql_num_rows(mysql_query("SELECT 1 FROM ".$config['db']['pre']."digs WHERE story_id='".addslashes($_GET['i'])."' AND user_id='".$_SESSION['duser']['id']."' LIMIT 1"));
	
		// Check that they havn't dugg it
		if(!$dugg)
		{
			// Update dugg count on story
			mysql_query("UPDATE `".$config['db']['pre']."stories` SET `story_digs` = story_digs+1,`story_last5` = story_last5+1 WHERE `story_id` =".addslashes($_GET['i'])." LIMIT 1 ;");
			// Insert digg into digs table
			mysql_query("INSERT INTO `".$config['db']['pre']."digs` ( `story_id` , `user_id` ) VALUES ('".addslashes($_GET['i'])."', '".$_SESSION['duser']['id']."');");
		
			// Check number of digs on story
			$digs = mysql_fetch_row(mysql_query("SELECT story_digs FROM ".$config['db']['pre']."stories WHERE story_id='".addslashes($_GET['i'])."' LIMIT 1"));
			
			// Register that they have dugg this story in session
			$_SESSION['dugg'][$_GET['i']] = true;
			
			// Return success and number of digs
			echo '1|'.$_GET['i'].'|'.$digs[0];
		}
		else
		{
			// User has already dugg this story
			echo '2|'.$_GET['i'].'|'.$digs[0];
		}
	}
	else
	{
		// User has already dugg this story
		echo '2|'.$_GET['i'].'|'.$digs[0];
	}
}
else
{
	// User isn't logged in
	echo '0|'.$_GET['i'].'|'.$digs[0];
}
?>